package cn.bjit.service.impl;

import cn.bjit.enums.BizCodeEnum;
import cn.bjit.enums.SenCodeEnum;
import cn.bjit.feign.CouponFeignService;
import cn.bjit.interceptor.LoginInterceptor;
import cn.bjit.mapper.UserMapper;
import cn.bjit.model.LoginUser;
import cn.bjit.model.UserDO;
import cn.bjit.request.NewUserCouponRequest;
import cn.bjit.request.UserLoginRequest;
import cn.bjit.request.UserRegisterRequest;
import cn.bjit.service.NotiyService;
import cn.bjit.service.UserService;
import cn.bjit.util.CommonUtil;
import cn.bjit.util.JWTUtil;
import cn.bjit.util.JsonData;
import cn.bjit.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Resource
    private NotiyService notiyService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private CouponFeignService couponFeignService;

    /**
     * 用户注册
     *
     * @param userRegisterRequest 等用于UserDO
     * @return
     */
      @Transactional(propagation = Propagation.REQUIRED)
//     @GlobalTransactional
    public JsonData register(UserRegisterRequest userRegisterRequest) {
        boolean checkCode = false;
        //如果邮箱不是空，则认为发送验证码了 code:USER_REGISTER:yangxing7758@qq.com
        if (StringUtils.isNotBlank(userRegisterRequest.getMail())) {
            checkCode = notiyService.checkCode(SenCodeEnum.USER_REGISTER, userRegisterRequest.getMail(), userRegisterRequest.getCode());
        }
        if (!checkCode) {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userRegisterRequest, userDO);

        userDO.setCreateTime(new Date());
        //设置密码
        //>8位随机数
        userDO.setSecret("$1$" + CommonUtil.getStringNumRandom(8));
        //>密码 加盐
        String cryptPwd = Md5Crypt.md5Crypt(userRegisterRequest.getPwd().getBytes(), userDO.getSecret());
        userDO.setPwd(cryptPwd);
        //唯一性验证
        if (checkUnique(userDO.getMail())) {//邮箱验证通过
            int rows = userMapper.insert(userDO);//插入信息
            log.info("rows{},注册成功{}", rows, userDO.toString());
            userRegisterInitTask(userDO); //新用户发送福利
            // int xx=1/0;
            return JsonData.buildSuccess();
        } else { //邮箱验证不通过
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_REPEAT);//账号已经存在
        }
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @return
     */
    @Override
    public JsonData login(UserLoginRequest userLoginRequest) {
          // >>1,根据用户输入的邮箱，到数据库中查询对应的记录
        List<UserDO> userDOList = userMapper.selectList(new QueryWrapper<UserDO>().eq("mail", userLoginRequest.getMail()));
        if(userDOList!=null&&userDOList.size()==1){ //查到了
            UserDO userDO = userDOList.get(0);//获取查询到的这条数据
            // >>2,用户密码加盐处理后和数据库中的做对比
            String pwdCrypt=Md5Crypt.md5Crypt(userLoginRequest.getPwd().getBytes(),userDO.getSecret());
             if(pwdCrypt.equals(userDO.getPwd())){ //如果相等，登录成功
                  //生成对应的token
                 LoginUser loginUser=new LoginUser();
                 BeanUtils.copyProperties(userDO,loginUser);
                 String token = JWTUtil.geneJsonWebToken(loginUser);
                 //
                 return JsonData.buildSuccess(token);
             }else{ //如果不相等，登录失败
                 return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
             }
        }else{ //查不到,提示账号或密码错误
           return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
        }
    }

    /**
     * 查询用户个人信息
     * @return
     * UserDO{  id ,name ,age}
     * UserVO{id，name}
     */
    public UserVO findUserDetail() {
       //获取连接器中的key
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        UserDO userDO=userMapper.selectOne(new QueryWrapper<UserDO>().eq("id",loginUser.getId()));
        UserVO userVO=new UserVO();
        BeanUtils.copyProperties(userDO,userVO);
        return userVO;
    }

    /**
     * 用户发送福利
     *
     * @param userDO
     */
    private void userRegisterInitTask(UserDO userDO) {
        NewUserCouponRequest newUserCouponRequest=new NewUserCouponRequest();
        newUserCouponRequest.setUserId(userDO.getId());
        newUserCouponRequest.setName(userDO.getName());
        JsonData jsonData = couponFeignService.addNewUserCoupon(newUserCouponRequest);
        if(jsonData.getCode()!=0){
             throw  new RuntimeException("优惠券领取失败！");
        }
        log.info("新用户发送优惠券{},结果{}",newUserCouponRequest.toString(),jsonData.toString());
    }

    /**
     * 验证邮箱是否唯一
     *
     * @param mail
     * @return
     */
    private boolean checkUnique(String mail) {
        QueryWrapper queryWrapper = new QueryWrapper<UserDO>().eq("mail", mail);
        List selectList = userMapper.selectList(queryWrapper); //插入数据库发送已经有了一个这样的邮箱
        return selectList.size() > 0 ? false : true;
    }
}
